<template>
  <div class="regression" ref="base" v-if="!is_create">
    <div class="title">
      <div class="create_task">
        <el-button type="primary" style="padding: 10px 15px; margin: 0 3px 0 0" @click="switch_status">创建任务
        </el-button>
      </div>
      <div class="time_search">
        <el-date-picker
            v-model="search_value"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
        </el-date-picker>
        <span style="margin-left: 4px">
        <el-button type="primary" icon="el-icon-search" class="time_search_button" @click="time_search">搜索</el-button>
      </span>
      </div>
    </div>
    <div class="detail-box">
      <el-dialog
          :title="testDetail"
          :visible.sync="detailStatus"
          width="1000px">
        <el-dialog
            width="860px"
            title="日志详情"
            :visible.sync="detailLog"
            append-to-body>
          <textarea cols="110" rows="30" disabled>
            {{ log_content }}
          </textarea>
        </el-dialog>
        <el-table :data="detailInfo" stripe height="500px" style="width: 100%">
          <el-table-column prop="case_name" label="用例名称" width="200px"></el-table-column>
          <el-table-column prop="status" label="测试状态" width="120px"></el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="220">
            <template slot-scope="scope">
              <span>{{ time_format(scope.row.create_time) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="modify_time" label="更新时间" width="220">
            <template slot-scope="scope">
              <span>{{ time_format(scope.row.modify_time) }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="log_path" label="日志" width="100">
            <template slot-scope="scope">
              <el-button @click="my_read_log(scope.row.log_path)" type="text" size="small">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
    <div class="modify-box">
      <el-dialog title="更改测试项" :visible.sync="dialogTableVisible" width="800px">
        <el-form :model="modifyForm" :rules="modify" ref="modifyForm" label-width="150px" class="demo-ruleForm">
          <el-form-item label="任务ID">
            <el-input v-model="modifyForm.uid" :disabled="true" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="测试版本" prop="version_name" style="width: 400px">
            <el-select
                v-model="modifyForm.version_name"
                placeholder="请选择测试版本"
                clearable
                @click.native="get_version"
                style="width: 400px;">
              <el-option
                  v-for="item in version_name_list"
                  :key="item.version_name"
                  :label="item.version_name"
                  :value="item.version_name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="测试用例" prop="case_name_list">
            <el-select
                v-model="modifyForm.case_name_list"
                multiple
                placeholder="请选择测试用例"
                @click.native="get_case_name"
                style="width: 400px;">
              <el-option
                  v-for="item in create_case_name_list"
                  :key="item.case_name"
                  :label="item.case_name"
                  :value="item.case_name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="报警机器人" prop="police" style="width: 400px">
            <el-select
                v-model="modifyForm.police"
                placeholder="请选择报警机器人"
                clearable
                @click.native="get_police_list"
                style="width: 400px;">
              <el-option
                  v-for="item in police_list"
                  :key="item.nickname"
                  :label="item.nickname"
                  :value="item.nickname">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="备注信息" prop="remarks" style="width: 500px;">
            <el-input type="textarea" v-model="modifyForm.remarks"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitModifyForm('modifyForm')" v-if="!modify_status">提交</el-button>
            <el-button type="primary" :loading="true" @click="submitModifyForm('modifyForm')" v-else>提交</el-button>
            <el-button @click="resetForm('modifyForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div class="content-box">
      <el-table
          class="table-css"
          ref="multipleTable"
          :data="this.tableData"
          stripe
          height="calc(100vh - 180px)"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
            prop="version_name"
            label="版本号"
            width="120"
            fixed>
        </el-table-column>
        <el-table-column
            label="状态"
            prop="status"
            width="180">
          <template slot-scope="scope">
          <span v-if="scope.row.status.toLowerCase() == 'running'">
            <el-button
                type="primary"
                style="padding: 6px 10px; margin: 0 3px 0 0; background-color: rgba(252,187,55,0.81); border-color: white; width: 71px">
              {{ scope.row.status }}
            </el-button>
          </span>
            <span v-else-if="scope.row.status.toLowerCase() == 'stop'">
            <el-button
                type="primary"
                style="padding: 6px 10px; margin: 0 3px 0 0; background-color: #a4adb6cf; border-color: white; width: 71px">
              {{ scope.row.status }}
            </el-button>
          </span>
            <span v-else-if="scope.row.status.toLowerCase() == 'success'">
            <el-button
                type="primary"
                style="padding: 6px 10px; margin: 0 3px 0 0; background-color: #6dd10abf; border-color: white; width: 71px">
              {{ scope.row.status }}
            </el-button>
          </span>
            <span v-else-if="scope.row.status.toLowerCase() == 'fail'">
            <el-button
                type="primary"
                style="padding: 6px 10px; margin: 0 3px 0 0; background-color: #FD4A4A92; border-color: white; width: 71px">
              {{ scope.row.status }}
            </el-button>
          </span>
            <span v-else>
            <el-button
                type="primary"
                style="padding: 6px 10px; margin: 0 3px 0 0; background-color: #A7A6A697; border-color: white; width: 71px">
              {{ scope.row.status }}
            </el-button>
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="220">
          <template slot-scope="scope">
            <span>{{ time_format(scope.row.create_time) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="modify_time" label="更新时间" width="220">
          <template slot-scope="scope">
            <span>{{ time_format(scope.row.modify_time) }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="police" label="报警机器人" width="200"/>
        <el-table-column prop="remarks" label="备注" width="260"/>
        <el-table-column fixed="right" label="操作" width="280">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status.toLowerCase() === 'pending'" @click="my_modify(scope.row)" type="text"
                       size="small">修改
            </el-button>
            <el-button v-else disabled @click="my_modify(scope.row)" type="text" size="small">修改</el-button>
            <el-button @click="my_detail(scope.row)" type="text" size="small">详情</el-button>

            <el-button v-if="scope.row.status.toLowerCase() === 'pending'" @click="my_start(scope.row)"
                       type="text"
                       size="small">启动
            </el-button>
            <el-button
                v-else-if="scope.row.status.toLowerCase() === 'kill'"
                @click="my_stop_or_continue(scope.row)"
                type="text"
                disabled
                size="small">停止
            </el-button>
            <el-button
                v-else-if="scope.row.status.toLowerCase() === 'running'"
                @click="my_stop_or_continue(scope.row)"
                type="text"
                size="small">停止
            </el-button>
            <el-button
                v-else-if="scope.row.status.toLowerCase() === 'stop'"
                @click="my_stop_or_continue(scope.row)"
                type="text"
                size="small">继续
            </el-button>
            <el-button v-else disabled @click="my_start(scope.row)" type="text" size="small">启动</el-button>

            <el-button
                v-if="scope.row.status.toLowerCase() !== 'pending' && scope.row.status.toLowerCase() !== 'success' &&
                      scope.row.status.toLowerCase() !== 'kill'"
                @click="my_kill(scope.row)"
                type="text"
                size="small">结束
            </el-button>
            <el-button v-else disabled @click="my_kill(scope.row)" type="text" size="small">结束</el-button>
            <el-button @click="my_delete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="base_bottom">
      <div class="my_select_button">
        <el-button type="primary" style="padding: 10px 15px; margin: 0 3px 0 0" @click="select_all">全选</el-button>
        <el-button type="primary" style="padding: 10px 15px; margin: 0 3px 0 0" @click="delete_all">全部删除</el-button>
      </div>
      <div class="my-pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes=this.pagesizes
            :page-size=this.pagesize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
        </el-pagination>
      </div>
    </div>
  </div>
  <div class="create-task" v-else>
    <i class="el-icon-circle-close go-back" @click="switch_status"></i>
    <el-form
        style="margin-top: 20px"
        :model="createForm"
        :rules="create_rules"
        ref="createForm"
        label-width="150px"
        class="demo-ruleForm">
      <el-form-item label="测试版本" prop="version_name" style="width: 400px">
        <el-select
            v-model="createForm.version_name"
            placeholder="请选择测试版本"
            clearable
            @click.native="get_version"
            style="width: 400px;">
          <el-option
              v-for="item in version_name_list"
              :key="item.version_name"
              :label="item.version_name"
              :value="item.version_name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="测试用例" prop="case_name_list">
        <el-select
            v-model="createForm.case_name_list"
            multiple
            placeholder="请选择测试用例"
            @click.native="get_case_name"
            style="width: 400px;">
          <el-option
              v-for="item in create_case_name_list"
              :key="item.case_name"
              :label="item.case_name"
              :value="item.case_name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报警设置" prop="police" style="width: 400px">
        <el-select
            v-model="createForm.police"
            placeholder="请选择报警机器人"
            clearable
            @click.native="get_police_list"
            style="width: 400px;">
          <el-option
              v-for="item in police_list"
              :key="item.nickname"
              :label="item.nickname"
              :value="item.nickname">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注信息" prop="remarks" style="width: 550px;">
        <el-input type="textarea" v-model="createForm.remarks"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('createForm')" v-if="!add_status">立即创建</el-button>
        <el-button type="primary" :loading="true" @click="submitForm('createForm')" v-else>立即创建</el-button>
        <el-button @click="resetForm('createForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import "@/my_constants"
import {
  get_test_info,
  query_filter,
  add_test,
  modify_test,
  delete_test_info,
  filter_query,
  start_task,
  stop_or_continue_task,
  kill_task,
  read_log,
  get_police
} from "@/js/regression";
import {delete_user, modify_user} from "@/js/user_manage";
import ElementUI from "element-ui";

export default {
  name: "Regression",
  beforeCreate() {
    // 提前获取详情
    get_test_info(1, 10).then(response => {
      this.tableData = response.data.data;
      this.total = response.data.total;
    })
  },
  data() {
    return {
      total: 0, //默认数据总数
      pagesizes: [10, 20, 50],//每页的数据条数
      pagesize: 10,//每页的数据条数
      currentPage: 1,
      tableData: [],
      // 全选
      multipleSelection: [],
      // 详情
      testDetail: '版本测试用例',
      detailStatus: false,
      detailLog: false,
      log_content: '',
      detailInfo: [],
      //  过滤器
      time_filter: '',
      // 时间搜索快速获取
      search_value: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      // 创建用户相关
      is_create: false,
      add_status: false,
      create_case_name_list: [],
      version_name_list: [],
      police_list: [],
      createForm: {
        case_name_list: '',
        version_name: '',
        remarks: '',
        police: '',
      },
      create_rules: {
        case_name_list: [
          {required: true, message: '请选择测试用例', trigger: 'blur'},
        ],
        version_name: [
          {required: true, message: '请选择测试版本', trigger: 'blur'},
        ],
      },
      // 修改
      dialogTableVisible: false,
      modify_status: false,
      modifyForm: {
        case_name_list: '',
        version_name: '',
        remarks: '',
        police: '',
      },
      modify: {
        case_name_list: [
          {required: true, message: '请选择测试用例', trigger: 'blur'},
        ],
        version_name: [
          {required: true, message: '请选择测试版本', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    get_version() {
      let params = {
        'method': 'get_version'
      }
      query_filter(params).then(response => {
        this.version_name_list = response.data.data
      })
    },
    get_case_name() {
      let params = {
        'method': 'get_case_name'
      }
      query_filter(params).then(response => {
        this.create_case_name_list = response.data.data
      })
    },
    // 创建任务状态切换
    switch_status() {
      if (!this.is_create) {
        this.is_create = true;
      } else {
        this.is_create = false;
      }
    },
    // 时间范围
    time_search() {
      // 标准时间 转时间戳
      if (!this.search_value) {
        get_test_info(this.currentPage, this.pagesize).then(response => {
          this.tableData = response.data.data;
          this.total = response.data.total;
        })
        return
      }
      let time1 = new Date(this.search_value[0]);
      let time2 = new Date(this.search_value[1]);
      let start_time = time1.getFullYear() + '-' + (time1.getMonth() + 1) + '-' + time1.getDate()
      let end_time = time2.getFullYear() + '-' + (time2.getMonth() + 1) + '-' + time2.getDate()
      this.time_filter = {
        'start_time': start_time,
        'end_time': end_time
      }
      filter_query(this.currentPage, this.pagesize, this.time_filter).then(response => {
        this.tableData = response.data.data;
        this.total = response.data.total;
      })
    },
    // 创建任务表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.createForm))
          let case_name_list = params.case_name_list.join(',')
          params.execute_user = localStorage.getItem('username')
          params.case_name_list = case_name_list
          add_test(params);
          this.resetForm(formName)
        } else {
          console.log('error submit!!');
          return false;
        }
        // 刷新数据
        this.reload_data()
        // 关闭
        this.switch_status()
      });
    },
    // 更改
    submitModifyForm(formName) {
      this.modify_status = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.modifyForm))
          let case_name_list = params.case_name_list.join(',')
          params.execute_user = localStorage.getItem('username')
          params.case_name_list = case_name_list
          modify_test(params).then(response => {
            if (response.data.status == 'success') {
              ElementUI.Message({
                showClose: true,
                message: '更改成功',
                type: 'success'
              });
              this.resetForm(formName)
              this.dialogTableVisible = false;
              this.modify_status = false;
              this.reload_data()
            } else {
              ElementUI.Message({
                showClose: true,
                message: response.data.message,
                type: 'error'
              });
            }
          })
        } else {
          ElementUI.Message({
            showClose: true,
            message: '更改失败, 请确认参数填写确认再提交',
            type: 'error'
          });
          return false;
        }
      });
    },
    // 清空创建任务表单参数
    resetForm(formName) {
      this.add_status = false;
      this.modify_status = false
      this.$refs[formName].resetFields();
    },
    // 分页器相关
    // 当前页数
    handleSizeChange(val) {
      this.pagesize = val;
      this.currentPage = 1;
      this.reload_data()
    },
    // 每页显示条数
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reload_data()
    },
    // 取消全选
    toggleSection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggRowSelection(row);
        });
      } else {
        this.$ref.multipleSelection.clearSelection();
      }
    },
    // 点击全选或选择框时出发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 全选
    select_all() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    // 时间显示格式
    time_format(time) {
      let year = new Date(time).getFullYear();
      let month = new Date(time).getMonth() + 1 < 10 ? "0" + (new Date(time).getMonth() + 1) : new Date(time).getMonth() + 1;
      let date = new Date(time).getDate() < 10 ? "0" + new Date(time).getDate() : new Date(time).getDate();
      let hh = new Date(time).getHours() < 10 ? "0" + new Date(time).getHours() : new Date(time).getHours();
      let mm = new Date(time).getMinutes() < 10 ? "0" + new Date(time).getMinutes() : new Date(time).getMinutes();
      let ss = new Date(time).getSeconds() < 10 ? "0" + new Date(time).getSeconds() : new Date(time).getSeconds();
      return year + "-" + month + "-" + date + "-" + " " + hh + ":" + mm + ':' + ss;
    },
    // 修改
    my_modify(val) {
      this.dialogTableVisible = true;
      let params = {
        'method': 'uid',
        'uid': val.uid
      }
      query_filter(params).then(response => {
        this.modifyForm = response.data.data
        if (response.data.data) {
          let case_name_list = response.data.data.case_name_list
          this.modifyForm.case_name_list = case_name_list.split(',')
        }
      })
    },
    // 详情
    my_detail(val) {
      this.detailStatus = true
      let params = {
        'method': 'regression',
        'regression': val.uid
      }
      query_filter(params).then(response => {
        this.detailInfo = response.data.data
        this.testDetail = '测试UID[ ' + val.uid + ' ]'
      })
    },
    // 启动
    my_start(val) {
      start_task(val)
      this.reload_data()
    },
    // 停止
    my_stop_or_continue(val) {
      console.log(val)
      stop_or_continue_task(val)
      this.reload_data()
    },
    // 结束
    my_kill(val) {
      kill_task(val)
      this.reload_data()
    },
    // 查看日志
    my_read_log(val) {
      this.detailLog = true;
      read_log(val).then(response => {
        this.log_content = response.data
      })
    },
    // 报警
    get_police_list() {
      get_police().then(response => {
        this.police_list = response.data.data
      })
    },

    // 删除
    my_delete(val) {
      if (!val) {
        return
      }
      // 确认
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delete_test_info(val).then(response => {
        });
        // 设置延迟，实现组件刷新
        setTimeout(() => {
          this.reload_data()
        }, 300)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 批量删除
    delete_all() {
      if (!this.multipleSelection.length) {
        return
      }
      // 确认
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delete_test_info(this.multipleSelection).then(response => {
        });
        // 设置延迟，实现组件刷新
        setTimeout(() => {
          this.reload_data()
        }, 300)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 刷新
    reload_data() {
      setTimeout(() => {
        if (this.time_filter) {
          console.log(this.time_filter)
          get_test_info(this.currentPage, this.pagesize, this.time_filter).then(response => {
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        } else if (this.field_filter) {
          console.log(this.field_filter)
          filter_query(this.currentPage, this.pagesize, this.field_filter).then(response => {
            console.log(response.data)
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        } else {
          get_test_info(this.currentPage, this.pagesize).then(response => {
            this.tableData = response.data.data;
            this.total = response.data.total;
          })
        }
      }, 1000)
    },
  },
  watch: {
    tableData: function () {
      this.$forceUpdate()
    },
  }
}
</script>

<style>
.regression {
  width: 100%;
  margin: 0 0 0 5px;

}

.regression:after {
  content: '';
  clear: both;
}

/* 创建任务 */
.title {
  height: 40px;
  margin: 10px 0;
}

.title:after {
  clear: both;
}

/* 关键字搜索 */
.create_task {
  float: left;
}

/* 按时间搜索 */
.time_search {
  float: right;
  margin-right: 20px;
}

.time_search_button {
  margin-left: 2px;
}

/* 创建任务按钮 */
.create_params_submit {
  margin-top: 10px;
  margin-left: 10px;
}

/* --------- end --------- */
.my_select_button {
  float: left;
}

.my-pagination {
  float: right;
  font-size: 14px;
  margin-right: 20px;
}

.base_bottom {
  margin: 10px 0;
  height: 40px;
}

/* 创建任务 */
.create-task {
  margin: 10px;
  padding: 5px;
  box-shadow: 10px 10px 20px #888888
}

/* 返回按钮 */
.go-back {
  float: right;
  font-size: 22px;
  padding: 5px;
  color: #c4bbbb;
}

.go-back:hover {
  color: #868181;
}
</style>
